/*
 * Copyright (c) 2016-2017 fulihui.com All right reserved
 * Project: information-core-170307
 * File name: VersionFormat.java
 */

package com.fulihui.usercore.common.util;

import org.near.toolkit.common.StringUtil;

import java.util.regex.Pattern;

/**
 * @author Willard.Hu on 2017/3/3 0003.
 */
public class VersionFormat {
    private static final Pattern regx = Pattern.compile("^\\d{1,2}\\.\\d{1,2}\\.\\d{1,2}$");

    public static int atoi(String version) {
        if (version == null) {
            return 0;
        }
        if (!regx.matcher(version).find()) {
            throw new IllegalArgumentException("version:" + version + " can't match RegEx");
        }
        String[] array = StringUtil.split(version, ".");
        int num = 0, n = 10000;
        for (String s : array) {
            num += Integer.parseInt(s) * n;
            n /= 100;
        }
        return num;
    }

    public static String itoa(int version) {
        if (version == 0) {
            return null;
        }
        StringBuilder res = new StringBuilder();
        while (version > 0) {
            String s = String.valueOf(version % 100);
            if (res.length() > 0) {
                s += ".";
            }
            res.insert(0, s);
            version /= 100;
        }
        return res.toString();
    }
}
